import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx'
import { Browser, BrowserHrm, Upload } from 'weaver-mobile-page'
import { withRouter } from 'react-router-dom';
import { Tools, TextareaItem, Icon, Select, Accordion, List, InputItem, DatePicker, Modal, Toast, Button, Tabs, Popover, Switch,Bubble } from 'weaver-mobile';
import FoldList from '../../../public/foldlist'
import  * as GoalDetailApis  from '../../../api/goal/goalDetail'
import * as Util from "../../../util";
import '../../../style/goal/goalDetail/goalRelateInfo.less';
const FormItem = List.FormItem
const getLabel = Tools.getLabel;
@inject("goalRelateInfoStore","goalDetailStore")
@withRouter
@observer
class GoalRelateInfo extends React.Component{

    constructor(props) {
        super(props)
        this.state = { ...props }
    }

    componentWillMount() {
        this.init()
        const { changeCategory, changeMaxUploadSize } = this.props.goalRelateInfoStore
        Tools.callApi({
            url: "/api/workrelate/goal/fileCategory",
            method: "GET",
            params: {},
            type: "json"
        }).then((data) => {
            if (data.status == 1) {
                changeCategory(data.secId)
                changeMaxUploadSize(data.maxsize)
            }
        })
    }

    

    componentWillReceiveProps(newProps) {
        // this.state.detail = newProps.detail
        this.init()
    }

    componentWillUnmount() {

    }



    init = () => {
        const { detailData,goalId,canedit,connectGoals,connectTasks } = this.props.goalDetailStore;
        const { changeGoalId, changeGoalDatas, changeTaskDatas, changeDocDatas, changeProcessDatas, changeCustomerDatas, 
            changeProjectDatas, changeFileDatas,changeConnectGoals,changeConnectTasks } = this.props.goalRelateInfoStore;
        const { relateCutomer,relateDocs,relateFileds,relateGoals,relateProjects,relateTasks,relateWorkFlows} = detailData;

        changeGoalId(goalId)
        changeTaskDatas(this.prehandleRelateDatas(relateTasks, "taskids"))
        changeGoalDatas(this.prehandleRelateDatas(relateGoals, "goalids"))
        changeDocDatas(this.prehandleRelateDatas(relateDocs, "docids"))
        changeProcessDatas(this.prehandleRelateDatas(relateWorkFlows, "wfids"))
        changeCustomerDatas(this.prehandleRelateDatas(relateCutomer, "crmids"))
        changeProjectDatas(this.prehandleRelateDatas(relateProjects, "projectids"))
        changeFileDatas(this.prehandleRelateDatas(relateFileds, "fileids"))
        changeConnectGoals(this.prehandleRelateDatas(connectGoals, "connectGoalids"))
        changeConnectTasks(this.prehandleRelateDatas(connectTasks, "connectTaskids"))
    }

    prehandleRelateDatas = (datas, fieldname) => {
        const { canedit } = this.props.goalDetailStore;
        datas = datas || []
        let newDatas = []
        if (["goalids", "taskids", "docids", "wfids", "crmids", "projectids","connectGoalids","connectTaskids"].indexOf(fieldname) > -1) {
            datas.forEach((d, i) => {
                let data = { ...d }
                canedit == true ? data.comsbtn = [
                    {
                        text: getLabel(91, '删除'),
                        onPress: () => { this.onDataDelete(fieldname, d.id) },
                        style: { backgroundColor: "rgba(170, 170, 170, 1)", color: 'white', padding: "0 15px" }
                    }
                ] :"";
                newDatas.push(data)
            })
        } else if (["fileids"].indexOf(fieldname) > -1) {
            datas.forEach((d, i) => {
                let data = { ...d }
                canedit == true ? data.comsbtn = [
                    {
                        text: getLabel(258,'下载'),
                        onPress: () => { this.onDataDownload(d.id, d.fileid) },
                        style: { backgroundColor: "rgba(77, 122, 216, 1)", color: 'white', padding: "0 15px" }
                    },
                    {
                        text: getLabel(91, '删除'),
                        onPress: () => { this.onDataDelete(fieldname, d.id) },
                        style: { backgroundColor: "rgba(170, 170, 170, 1)", color: 'white', padding: "0 15px" }
                    }
                ]:data.comsbtn = [
                    {
                        text: getLabel(258,'下载'),
                        onPress: () => { this.onDataDownload(d.id,d.fileid) },
                        style: { backgroundColor: "rgba(77, 122, 216, 1)", color: 'white', padding: "0 15px" }
                    }
                ]
                newDatas.push(data)
            })
        }
        return newDatas
    }

    onDataDelete = (fieldname, deleteval) => {
        const { detailData, changeDetailData} = this.props.goalDetailStore;
        const { goalId, taskDatas, goalDatas, docDatas, processDatas, customerDatas, projectDatas, fileDatas, connectGoals, connectTasks} = this.props.goalRelateInfoStore;
        let targetDatas = []
        if (fieldname === "taskids") {
            targetDatas = taskDatas
        } else if (fieldname === "goalids") {
            targetDatas = goalDatas
        } else if (fieldname === "docids") {
            targetDatas = docDatas
        } else if (fieldname === "wfids") {
            targetDatas = processDatas
        } else if (fieldname === "crmids") {
            targetDatas = customerDatas
        } else if (fieldname === "projectids") {
            targetDatas = processDatas
        } else if (fieldname === "fileids") {
            targetDatas = fileDatas
        }
        let content =  targetDatas.filter((d, i) => { return d.id != deleteval }).map((d, i) => { return d.id }).join(",");
        if(content != ""){
            content = "," + content + ","
        }
        GoalDetailApis.editGoalField({
            goalId,
            fieldname,
            fieldvalue: fieldname === "fileids" ? deleteval : content,
            logDelvalue: fieldname === "fileids" ? "" : deleteval,
            fieldtype: fieldname === "fileids" ? "del" :"",
        }).then(res => {
            if (res.status == "1") {
                Bubble.success(getLabel(83472,'删除成功!'), 1)
                fieldname === "goalids" && changeDetailData({ ...detailData, relateGoals: detailData.relateGoals.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "taskids" && changeDetailData({ ...detailData, relateTasks: detailData.relateTasks.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "docids" && changeDetailData({ ...detailData, relateDocs: detailData.relateDocs.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "wfids" && changeDetailData({ ...detailData, relateWorkFlows: detailData.relateWorkFlows.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "crmids" && changeDetailData({ ...detailData, relateCutomer: detailData.relateCutomer.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "projectids" && changeDetailData({ ...detailData, relateProjects: detailData.relateProjects.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "fileids" && changeDetailData({ ...detailData, relateFileds: detailData.relateFileds.filter((d, i) => { return d.id != deleteval }) })
            } else {
                Bubble.error(getLabel(83472,'删除成功!'),1)
            }
        })
    }

    onDataDownload = (id,fileid) => {
        const { goalId } = this.props.goalRelateInfoStore
        window.downloadFile(id, fileid, goalId, "1")
    }

    onRelateInfoChange = (goalId, fieldname, newDatas, fieldvalue) => {
        const {detailData , changeDetailData } = this.props.goalDetailStore
        const { goalDatas, taskDatas, docDatas, processDatas, customerDatas, projectDatas, fileDatas } = this.props.goalRelateInfoStore
        let oldDatas = []
        if (fieldname === "goalids") {
            oldDatas = goalDatas
        } else if (fieldname === "taskids") {
            oldDatas = taskDatas
        } else if (fieldname === "docids") {
            oldDatas = docDatas
        } else if (fieldname === "wfids") {
            oldDatas = processDatas
        } else if (fieldname === "crmids") {
            oldDatas = customerDatas
        } else if (fieldname === "projectids") {
            oldDatas = projectDatas
        } else if (fieldname === "fileids") {
            oldDatas = fileDatas
        }
        let newIdsStr = newDatas.length > 0 ? ","+newDatas.map((d, i) => { return d.id }).join(",")+"," : "";
        let oldIdsStr = oldDatas.length > 0 ? ","+oldDatas.map((d, i) => { return d.id }).join(",")+"," : "";
        let logDelValue = Util.ArrayDiffer(oldIdsStr,newIdsStr,1);
        let logAddValue = Util.ArrayDiffer(oldIdsStr,newIdsStr.split(","),2);
        if (newIdsStr !== oldIdsStr) {
            GoalDetailApis.editGoalField({
                goalId,
                fieldname,
                fieldvalue: fieldname != "fileids" ? newIdsStr : fieldvalue,
                logDelValue,
                logAddValue,
            }).then(res => {
                if (res.status) {
                    if (fieldname !== "fileids") {
                        Bubble.success(getLabel(31439,'更新成功'), 1)
                    }
                    fieldname === "goalids" && changeDetailData({ ...detailData, relateGoals: newDatas })
                    fieldname === "taskids" && changeDetailData({ ...detailData, relateTasks: newDatas })
                    fieldname === "docids" && changeDetailData({ ...detailData, relateDocs: newDatas })
                    fieldname === "wfids" && changeDetailData({ ...detailData, relateWorkFlows: newDatas })
                    fieldname === "crmids" && changeDetailData({ ...detailData, relateCutomer: newDatas })
                    fieldname === "projectids" && changeDetailData({ ...detailData, relateProjects: newDatas })
                    fieldname === "fileids" && changeDetailData({ ...detailData, relateFileds: newDatas })
                } else {
                    if (fieldname !== "fileids") {
                        Bubble.fail(getLabel('25009','失败'), 1)
                    }
                }
            })
        }
    }

    onUploadDatasChange = (datas) => {
        const { goalId } = this.props.goalDetailStore
        const {  fileDatas, changeFileDatas } = this.props.goalRelateInfoStore
        let newFileDatas = [...fileDatas]
        let fieldvalue = ""
        datas.forEach((data, i) => {
            if (newFileDatas.indexOf(data.id) == -1) {
                data.size = data.filesize
                data.fileid = data.imagefileid  // 重置fileid
                newFileDatas.push(data)
                fieldvalue = fieldvalue + data.id + ","
            }
        })
        this.onRelateInfoChange(goalId, "fileids", newFileDatas, fieldvalue)
    }

    

    render() {
        const { goalId, goalDetailRelateGoalBrowserStore, goalDetailRelateTaskBrowserStore, goalDetailRelateDocBrowserStore,
            goalDetailRelateProcessBrowserStore, goalDetailRelateCustomerBrowserStore, goalDetailRelateProjectBrowserStore,
            goalDetailRelateFileBrowserStore,goalDetailConnectGoalsBrowserStore,goalDetailConnectTasksBrowserStore,
            goalDatas, taskDatas, docDatas, processDatas, customerDatas, projectDatas,connectGoals,connectTasks,
            goalFoldlistDatas, taskFoldlistDatas, docFoldlistDatas, processFoldlistDatas, customerFoldlistDatas,
            projectFoldlistDatas, fileFoldlistDatas,connectGoalsFoldListDatas,connectTasksFoldListDatas, category, maxUploadSize } = this.props.goalRelateInfoStore
        const {canedit} = this.props.goalDetailStore;    
        return (
            <div className="workrelate-mobile-relateinfo-wrapper">
                <FoldList
                    data={goalFoldlistDatas}
                    showseq={false}
                    headColor={"#96358A"}
                    headIconclass={"executive-force"}
                    headIconsize={"xs"}
                    headIconStyle={{ width: 25 }}
                    count={goalFoldlistDatas.length}
                    title={getLabel(330,'目标')}
                    bottomBorderColor={"#eee"}
                    open={true}
                    onItemClick={(dataid) => {
                        window.openAppLink(null, dataid, "wrlgoal", null, null)
                    }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com:<Browser
                                store={goalDetailRelateGoalBrowserStore}
                                dataURL={"/api/public/browser/data/"}
                                isSingle={false}
                                type={"wrlgoal"}
                                dataParams={{ parentid: goalId }}
                                onChange={(...arg) => {
                                    this.onRelateInfoChange(goalId, "goalids", toJS(arg[2]))
                                }}
                                valueArray={goalDatas}
                            />,
                            store:goalDetailRelateGoalBrowserStore
                        }
                    }
                    hasRight = {canedit}
                />
                <FoldList
                    data={taskFoldlistDatas}
                    showseq={false}
                    headColor={"#1A57A0"}
                    headIconclass={"related-tasks"}
                    headIconsize={"xs"}
                    headIconStyle={{ width: 25 }}
                    count={taskFoldlistDatas.length}
                    title={getLabel(1332, '任务')}
                    bottomBorderColor={"#eee"}
                    open={true}
                    onItemClick={(dataid) => {window.openAppLink(null, dataid, "wrltask", null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                store={goalDetailRelateTaskBrowserStore}
                                dataURL={"/api/public/browser/data/"}
                                isSingle={false}
                                type={"wrltsk"}
                                dataParams={{ parentid: -1 }}
                                onChange={(...arg) => {
                                    this.onRelateInfoChange(goalId, "taskids", toJS(arg[2]))
                                }}
                                valueArray={taskDatas}
                            />,
                            store:goalDetailRelateTaskBrowserStore
                        }
                       
                    }
                    hasRight = {canedit}
                />
                <FoldList
                    data={docFoldlistDatas}
                    showseq={false}
                    headColor={"#F14A2D"}
                    headIconclass={"currency"}
                    headIconsize={"xs"}
                    headIconStyle={{ width: 25 }}
                    count={docFoldlistDatas.length}
                    title={getLabel(58, '文档')}
                    bottomBorderColor={"#eee"}
                    open={true}
                    onItemClick={(dataid) => { window.openAppLink(null, dataid, 37, null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                    store={goalDetailRelateDocBrowserStore}
                                    dataURL={"/api/public/browser/data/"}
                                    isSingle={false}
                                    type={9}
                                    onChange={(...arg) => {
                                        this.onRelateInfoChange(goalId, "docids", toJS(arg[2]))
                                    }}
                                    valueArray={docDatas}
                                />,
                            store:goalDetailRelateDocBrowserStore
                        }
                    }
                    hasRight = {canedit}
                />
                <FoldList
                    data={processFoldlistDatas}
                    showseq={false}
                    headColor={"#2F4F4F"}
                    headIconclass={"process"}
                    headIconsize={"xs"}
                    headIconStyle={{ width: 25 }}
                    count={processFoldlistDatas.length}
                    title={getLabel(18015, '流程')}
                    bottomBorderColor={"#eee"}
                    open={true}
                    onItemClick={(dataid) => { window.openAppLink(null, dataid, 152, null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                    store={goalDetailRelateProcessBrowserStore}
                                    dataURL={"/api/public/browser/data/"}
                                    isSingle={false}
                                    type={16}
                                    onChange={(...arg) => {
                                        this.onRelateInfoChange(goalId, "wfids", toJS(arg[2]))
                                    }}
                                    valueArray={processDatas}
                                />,
                                store:goalDetailRelateProcessBrowserStore
                        }   
                    }
                    hasRight = {canedit}
                />
                <FoldList
                    data={customerFoldlistDatas}
                    showseq={false}
                    headColor={"#808000"}
                    headIconclass={"relevant-customer"}
                    headIconsize={"xs"}
                    headIconStyle={{ width: 25 }}
                    count={customerFoldlistDatas.length}
                    title={getLabel(136, '客户')}
                    bottomBorderColor={"#eee"}
                    open={true}
                    onItemClick={(dataid) => {  window.openAppLink(null, dataid, 7, null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                    store={goalDetailRelateCustomerBrowserStore}
                                    dataURL={"/api/public/browser/data/"}
                                    isSingle={false}
                                    type={7}
                                    onChange={(...arg) => {
                                        this.onRelateInfoChange(goalId, "crmids", toJS(arg[2]))
                                    }}
                                    valueArray={customerDatas}
                                />,
                                store:goalDetailRelateCustomerBrowserStore
                        }    
                    }
                    hasRight = {canedit}
                />
                <FoldList
                    data={projectFoldlistDatas}
                    showseq={false}
                    headColor={"#6B8E23"}
                    headIconclass={"relevant-project"}
                    headIconsize={"xs"}
                    headIconStyle={{ width: 25 }}
                    count={projectFoldlistDatas.length}
                    title={getLabel(101, '项目')}
                    bottomBorderColor={"#eee"}
                    open={true}
                    onItemClick={(dataid) => { window.openAppLink(null, dataid, 8, null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                    store={goalDetailRelateProjectBrowserStore}
                                    dataURL={"/api/public/browser/data/"}
                                    isSingle={false}
                                    type={8}
                                    onChange={(...arg) => {
                                        this.onRelateInfoChange(goalId, "projectids", toJS(arg[2]))
                                    }}
                                    valueArray={projectDatas}
                                />,
                                store:goalDetailRelateProjectBrowserStore
                        }
                    }
                    hasRight = {canedit}
                />
                <FoldList
                    data={fileFoldlistDatas}
                    showseq={false}
                    headColor={"#CD5C5C"}
                    headIconclass={"enclosure-01"}
                    headIconsize={"xs"}
                    headIconStyle={{ width: 25 }}
                    count={fileFoldlistDatas.length}
                    title={getLabel(156, '附件')}
                    bottomBorderColor={"#eee"}
                    open={true}
                    onItemClick={(dataid) => { window.openDoc(dataid, goalId, "2") }}
                    itemBottomOffset={0}
                    addIconIsUploader={true}
                    uploader={
                        {
                            com:  <Upload
                                    store={goalDetailRelateFileBrowserStore}
                                    // datas={relateAttachment}
                                    title={""}
                                    uploadUrl={'/api/doc/upload/uploadFile2Doc?category=' + category}
                                    editable={false}
                                    viewAttr={"2"}
                                    onChange={(ids, datas) => { this.onUploadDatasChange(datas) }}
                                    maxUploadSize={ maxUploadSize }
                                    // maxFilesNumber={ 16 }
                                    // totalMaxUploadSize={ 300 }
                                    showUploader={true}
                                    showUploadTime={true}
                                />,
                            store: goalDetailRelateFileBrowserStore
                        }
                    }
                    hasRight = {canedit}
                />
                {connectGoalsFoldListDatas && connectGoalsFoldListDatas.length > 0 && <FoldList
                    data={connectGoalsFoldListDatas}
                    showseq={false}
                    headColor={"#F14A2D"}
                    headIconclass={"executive-force"}
                    headIconsize={"xs"}
                    headIconStyle={{ width: 25 }}
                    count={connectGoalsFoldListDatas.length}
                    title={getLabel(508805,'关联了此目标的${word}').replace('${word}',getLabel(330,'目标'))}
                    bottomBorderColor={"#eee"}
                    open={true}
                    onItemClick={(dataid) => { window.openAppLink(null, dataid, "wrlgoal", null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                    store={goalDetailConnectGoalsBrowserStore}
                                    dataURL={"/api/public/browser/data/"}
                                    isSingle={false}
                                    type={"wrlgoal"}
                                    // onChange={(...arg) => {
                                    //     this.onRelateInfoChange(goalId, "connectGoalids", toJS(arg[2]))
                                    // }}
                                    valueArray={connectGoals}
                                />,
                                store:goalDetailConnectGoalsBrowserStore
                        }
                    }
                    hasRight = {false}
                />}
                {connectTasksFoldListDatas && connectTasksFoldListDatas.length > 0 && <FoldList
                    data={connectTasksFoldListDatas}
                    showseq={false}
                    headColor={"#F14A2D"}
                    headIconclass={"related-tasks"}
                    headIconsize={"xs"}
                    headIconStyle={{ width: 25 }}
                    count={connectTasksFoldListDatas.length}
                    title={getLabel(508805,'关联了此目标的${word}').replace('${word}',getLabel(1332, '任务'))}
                    bottomBorderColor={"#eee"}
                    open={true}
                    onItemClick={(dataid) => { window.openAppLink(null, dataid, "wrltask", null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                    store={goalDetailConnectTasksBrowserStore}
                                    dataURL={"/api/public/browser/data/"}
                                    isSingle={false}
                                    type={"wrltsk"}
                                    // onChange={(...arg) => {
                                    //     this.onRelateInfoChange(goalId, "projectids", toJS(arg[2]))
                                    // }}
                                    valueArray={connectTasks}
                                />,
                                store:goalDetailConnectTasksBrowserStore
                        }
                    }
                    hasRight = {false}
                />
                }
            </div>
        )
    }


}
export default GoalRelateInfo;